using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Destructiable : MonoBehaviour
{
    // 总血量
    public int maxHP = 100;
    // 当前血量
    private int currentHP;

    // 损坏的集合
    public List<Sprite> injuredSpriteList;
    private SpriteRenderer spriteRenderer;
    // 爆炸云预制
    private GameObject boomPrefab;

    // 检测碰撞 销毁
    private void OnCollisionEnter2D(Collision2D collision2D)
    {
        TakeDamage((int)(collision2D.relativeVelocity.magnitude*10));

    }
    // 受伤方法
    public void TakeDamage(int damage) {
        currentHP -= damage;

        if (currentHP <= 0)
        {
            Dead();
        } else
        {
            Sprite beforeSprite = spriteRenderer.sprite;
            int index = (int)((maxHP - currentHP)/(maxHP/(injuredSpriteList.Count + 1.0f))) - 1;
            if (index != -1)
            {
                spriteRenderer.sprite = injuredSpriteList[index];
            }
            if (beforeSprite != spriteRenderer.sprite)
            {
                PlayAduioCollision();
            }
        }
    }

    // 摧毁音效
    protected virtual void PlayAduioCollision()
    {
        AudioManager.Instance.PlayWoodCollision(transform.position);
    }
    protected virtual void PlayAudioDestoryed()
    {
        AudioManager.Instance.PlayWoodDestory(transform.position);
    }

    

    // 销毁死亡
    public virtual void Dead()
    {
        PlayAudioDestoryed();
        GameObject.Instantiate(boomPrefab, transform.position, Quaternion.identity);
        Destroy(gameObject);
    }

    // Start is called before the first frame update
    void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        currentHP = maxHP;
        boomPrefab = Resources.Load<GameObject>("Boom1");
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    
}
